package util;

import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.widget.ImageView;

/**
 * Created by chuanyhu on 2014/10/2.
 */
public class MatrixUtil {

    public static Rect  getCenterClip(Rect clipRect,Rect srcRect){
        Matrix matrix = new Matrix();
        RectF drawableRect = new RectF(srcRect);
        RectF viewRect = new RectF(clipRect );
        matrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
        float wscale =  drawableRect.width()/(float)viewRect.width();
        float hscale =  drawableRect.height()/(float)viewRect.height();
        float zoomScale = wscale > hscale ? wscale/hscale : hscale/wscale;
        matrix.postScale(zoomScale, zoomScale, viewRect.width() / 2, viewRect.height() / 2);

        Matrix inverse = new Matrix();
        boolean flag =matrix.invert(inverse);
        RectF resultRect =new RectF();
        inverse.mapRect(resultRect,viewRect);

        Rect retRect = new Rect( (int)resultRect.left, (int)resultRect.top, (int)resultRect.right, (int)resultRect.bottom );

        return retRect;
    }

    public static Rect  getClipRectFromImageView(ImageView imgView){
        Rect clipRect = new Rect(0,0,imgView.getWidth(),imgView.getHeight());

        Matrix inverse = new Matrix();

        boolean flag = imgView.getImageMatrix().invert(inverse);
        RectF resultRect =new RectF();
        inverse.mapRect(resultRect, new RectF(clipRect));
        Rect retRect = new Rect( (int)resultRect.left, (int)resultRect.top, (int)resultRect.right, (int)resultRect.bottom );
        return retRect;
    }

    public static Matrix getMatrix4Rect2Rect(Rect drawableRect ,Rect viewRect){
        Matrix matrix = new Matrix();
        RectF srcRect = new RectF(drawableRect);
        RectF destRect = new RectF(viewRect );
        matrix.setRectToRect(srcRect, destRect, Matrix.ScaleToFit.CENTER);

        return matrix;
    }
}
